Lesson 6 - intermediate exercise
For each scenario write code to solve it.
Scenario - Move a character around the screen using keys.
# imports needed for pygame
import pygame
import sys
import os
from pygame.locals import *
# set up some colours!
blue = (0,0,255)
black = (0 ,0 ,0)
# set up game window
pygame.init()
window = pygame.display.set_mode((600,400))
pygame.display.set_caption("bounce")
screen = pygame.display.get_surface()
# timer used to control animation
timer = pygame.time.Clock()
xpos = 200
ypos = 150
# main loop
while True:
# deal with events.
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
key = pygame.key.get_pressed()
if key[K_LEFT]:
xpos-=5
if key[K_RIGHT]:
xpos+=5
if key[K_UP]:
ypos-=5
if key[K_DOWN]:
ypos+=5
# clear the view
window.fill(black)
# draw the circle and update
pygame.draw.rect(window, blue, (xpos, ypos, 20, 10) )
pygame.display.update()
timer.tick(40)
Toggle answer
Scenario - Draw a rectangle which starts with size 30, 20 and ends up as 300, 200. It will increase in size by 2 every half a second. (hint - this will need a pygame clock)
# imports needed for pygame
import pygame
import sys
import os
from pygame.locals import *
# set up some colours!
red = (255,0,0)
black = (0,0,0)
# set up game window
pygame.init()
window = pygame.display.set_mode((600,400))
pygame.display.set_caption("growing rectangle")
screen = pygame.display.get_surface()
# timer used to control animation
timer = pygame.time.Clock()
xsize = 30
ysize = 20
# main loop
while True:
# deal with events.
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# clear the view
window.fill(black)
# draw the rectangle and update
pygame.draw.rect(window, red, (300 - (xsize / 2), 200 - (ysize / 2), xsize, ysize) )
pygame.display.update()
if xsize <= 300:
xsize += 2
ysize += 2
timer.tick(40)
Toggle answer